﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Publicuse.Util
{
    /// <summary>
    /// JSON工具类
    /// </summary>
    public class JsonUtil
    {
        public static string ToJson(object val)
        {
            try { return JsonConvert.SerializeObject(val); }
            catch { return null; }
        }

        public static T ToObject<T>(string json)
        {
            T data = default(T);
            try
            {
                json = Regex.Replace(json, @"\s", "");
                data = JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                var msg = ex.Message;
            }
            return data;
        }

        public static T ToObject<T>(string json, out string msg)
        {
            msg = string.Empty;
            T data = default(T);
            try
            {
                data = JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return data;
        }

        /// <summary>
        /// 数据转为json对象
        /// </summary>
        /// <param name="data"></param>
        /// <param name="dateFormatString"></param>
        /// <returns></returns>
        public static string RendData(object data)
        {
            JsonSerializerSettings setting = new JsonSerializerSettings();
            return JsonConvert.SerializeObject(data, setting);
        }

        /// <summary>
        /// json 字符串转为实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <param name="dateFormatString"></param>
        /// <returns></returns>
        public static T UnRendResult<T>(string json, string dateFormatString = "yyyy-MM-dd HH:mm:ss") where T : class
        {
            json = Regex.Replace(json, @"\s", "");
            JsonSerializerSettings setting = new JsonSerializerSettings();
            T result = JsonConvert.DeserializeObject<T>(json, setting);
            return result;
        }

        /// <summary>
        /// 反序列化Json数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsons"></param>
        /// <returns></returns>
        public static List<T> UnRendResults<T>(string jsons) where T : class
        {
            jsons = Regex.Replace(jsons, @"\s", "");
            List<T> list = new List<T>();
            list = JsonConvert.DeserializeObject<List<T>>(jsons);
            return list;

        }

        /// <summary>
        /// 转换对象集合为JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ListToJSON<T>(List<T> list)
        {
            string result = string.Empty;
            DataContractJsonSerializer json = new DataContractJsonSerializer(list.GetType());
            //序列化
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, list);
                result = Encoding.UTF8.GetString(stream.ToArray());
            }
            return result;
        }

        /// <summary>
        /// 字典类型转化为对象
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static T DicToObject<T>(Dictionary<string, string> dic) where T : new()
        {
            var entity = new T();
            try
            {
                if (dic == null)
                    return entity;

                foreach (var d in dic)
                {
                    var pros = entity.GetType().GetProperties();
                    foreach (var item in pros)
                    {
                        if (string.Compare(d.Key, item.Name) == 0)
                        {
                            switch (item.PropertyType.FullName)
                            {
                                case "System.String":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, d.Value);
                                    break;
                                case "System.Int32":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToInt32(d.Value));
                                    break;
                                case "System.Int64":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToInt64(d.Value));
                                    break;
                                case "System.Double":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToDouble(d.Value));
                                    break;
                                case "System.DateTime":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToDateTime(d.Value));
                                    break;
                                case "System.Decimal":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToDecimal(d.Value));
                                    break;
                                case "System.Boolean":
                                    entity.GetType().GetProperty(item.Name).SetValue(entity, Convert.ToBoolean(d.Value));
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
            return entity;
        }

        /// <summary>
        ///Get请求参数转换成字典集合 
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static Dictionary<string, string> QuerystrToDictionary(string data)
        {
            Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
            foreach (string key in data.Split('&'))
            {
                var item = key.Split('=');
                if (item.Length == 2)
                {
                    if (string.Compare(item[1], "undefined", true) != 0)
                    {
                        if (keyValuePairs.ContainsKey(item[0]))
                        {
                            keyValuePairs.Remove(item[0], out var msgb);
                            {
                                if (string.IsNullOrEmpty(msgb))
                                {
                                    keyValuePairs.Add(item[0], item[1]);
                                }
                            }
                        }
                        else
                        {
                            keyValuePairs.Add(item[0], item[1]);
                        }
                    }
                }
                else
                {
                    if (keyValuePairs.ContainsKey(item[0]))
                    {
                        keyValuePairs.Remove(item[0], out var msgb);
                        {
                            if (string.IsNullOrEmpty(msgb))
                            {
                                keyValuePairs.Add(item[0], string.Empty);
                            }
                        }
                    }
                    else
                    {
                        keyValuePairs.Add(item[0], string.Empty);
                    }
                }
            }
            return keyValuePairs;
        }

        /// <summary>
        /// 字符串转字典
        /// </summary>
        /// <param name="jsonData"></param>
        /// <returns></returns>
        public static Dictionary<string, string> JsonToDictionaryString(string jsonData)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// 将json数据反序列化为Dictionary字典
        /// </summary>  
        /// <param name="jsonData">json数据</param>  
        /// <returns></returns>  
        public static Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static Dictionary<string, string> JsonToDictionaryb(string jsonData)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonData);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>  
        /// 将Dictionary序列化为json数据  
        /// </summary>  
        /// <param name="jsonData">json数据</param>  
        /// <returns></returns>  
        public static string DictionaryToJson(Dictionary<string, object> dic)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.SerializeObject(dic);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string DictionaryToJson(IDictionary<string, Object> dic)
        {
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return JsonConvert.SerializeObject(dic);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

    };
}
